
import java.awt.Image;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;
import java.util.Timer;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.sun.jimi.core.Jimi;
import com.sun.jimi.core.JimiUtils;

public class UrlToImage {
	
	public static final int oneSec = 1000;
	
	public static final int oneMin = oneSec * 60;
	
	public static final int oneHour = oneMin * 60;
	
	public static final int oneDay = oneHour * 24;
	
	public static final int thumWidth = 128;
	
	public static final int thumHeight = 128;
	
	public static List<ShotVO> getShotList() {
		ShotDAO dao = new ShotDAO();
		return dao.selectOnVisibility();
	}
	
	public static List<ScreenShotVO> getScreenShotPath() {
		ScreenShotDAO dao = new ScreenShotDAO();
		return dao.selectScreenShotPath();
	}
	
	public static void makeThumbnailImage(File filePath) {
		try {
			Image thmbImage = JimiUtils.getThumbnail(new FileInputStream(filePath), thumWidth, thumHeight,
					Jimi.IN_MEMORY, false);
			String outFilePath = filePath.getPath();
			outFilePath = outFilePath.substring(0, outFilePath.lastIndexOf("."));
			outFilePath += ".jpg";
			Jimi.putImage(thmbImage, outFilePath);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		ResourceBundle bundle = ResourceBundle.getBundle("urltoimg");
		String filepath = bundle.getString("filepath");
		String mirrorpath = bundle.getString("mirrorpath");
		
		Information info = new Information();
		ExecutorService 
			takeScreenExecutor = Executors.newFixedThreadPool(11); 
		CompletionService<ScreenShotVO> 
			takeScreencompletionService = new ExecutorCompletionService<ScreenShotVO>(takeScreenExecutor);
		Thread 
			completionHandler = Executors.defaultThreadFactory()
				.newThread(new TakeScreenCompletionHandler(mirrorpath, info, takeScreencompletionService));
		completionHandler.start();
		
		Timer autoFlushTimer = new Timer();
		autoFlushTimer.schedule(new AutoFlushTask(info, takeScreencompletionService, filepath, mirrorpath), oneHour, oneHour);
		
		String cmdLine = null;
		long start = System.currentTimeMillis();
		while( true ) {
			System.out.print(">> ");
			try {
				cmdLine = (new BufferedReader(new InputStreamReader(System.in))).readLine();
				if( cmdLine != null && cmdLine.equalsIgnoreCase("exit") )
					break;
				else if( cmdLine != null && cmdLine.equalsIgnoreCase("auto-flush") ) {
					List<ShotVO> shotList = UrlToImage.getShotList();
					int count = 1;
					if( shotList != null ) {
						System.out.println("auto-flush start with "+shotList.size()+" job at "+new Date());
						for(int i=0; i<shotList.size(); i++) {
							TakeScreen t = new TakeScreen(shotList.get(i).getReportsId(), shotList.get(i).getPageUrl(), filepath, mirrorpath);
							takeScreencompletionService.submit(t);
							info.incrementReserved();
							System.out.println("submit at "+count+": "+shotList.get(i).getPageUrl());
							Thread.sleep(1000);
							++count;
						}
					}
					System.out.println("auto-flush done at "+new Date());
				}
				else if( cmdLine != null && cmdLine.equalsIgnoreCase("make-thumb") ) {
					List<ScreenShotVO> screenShotList = UrlToImage.getScreenShotPath();
					int count = 1;
					if( screenShotList != null ) {
						System.out.println("make-thumb start with "+screenShotList.size()+" job at "+new Date());
						for(int i=0; i<screenShotList.size(); i++) {
							String filename = screenShotList.get(i).getFileName();
							File thmbFile = new File(mirrorpath+filename.substring(filename.lastIndexOf("/")));
							System.out.println("submit at "+count+": "+filename);
							makeThumbnailImage(thmbFile);
							++count;
						}
					}
					System.out.println("make-thumb done at "+new Date());
				}
				else if( cmdLine != null && cmdLine.equalsIgnoreCase("info") ) {
					double sec = (System.currentTimeMillis()-start)/1000.0;
					double min = sec/60.0;
					DecimalFormat df = new DecimalFormat(",##0.00");
					System.out.println(
							"-- Runtime: "+sec+" sec("+df.format(min)+" min)"+
							"\n-- Reserved task: "+info.getReserved()+
							"\n-- Completed task: "+info.getTotal()+
							"\n---- Success task: "+info.getSuccess()+
							"\n---- Failure task: "+info.getFailure());
				}
			}
			catch (InterruptedException e) { }
			catch (IOException e) { }
		}
		autoFlushTimer.cancel();
		completionHandler.interrupt();
		takeScreenExecutor.shutdownNow();
	}
	
}
